/*
 * @Description: EXECEL层级间匹配关系面板
 * @Author: Rfan
 * @Date: 2022-05-06 12:06:39
 * @LastEditTime: 2022-08-09 19:42:32
 */

import { forwardRef, Ref, useEffect, useImperativeHandle, useState } from 'react';
import { Button, Form, Select, Space } from 'antd';
import { MinusCircleOutlined, PlusOutlined, SwapOutlined } from '@ant-design/icons';
import { useBatchManageContext } from '../../../../contexts/BatchManageContext';
import {
  deleteTemplateLevelList,
  fetchTemplateLevelList,
  saveTemplateLevelList
} from '@/api/accession';
import type { ILevel } from '@/interfaces/archiveType';

const { Option } = Select;

const LevelLink = forwardRef((props: any, ref: Ref<unknown>) => {
  const { upperLevel, lowerLevel, levelMetadata, list } = props;
  const [form] = Form.useForm();

  useImperativeHandle(ref, () => ({
    submit: () => {
      console.log(`${upperLevel?.levelName} submit`);
      form.submit();
    }
  }));

  const deleteItem = (remove: any, key: number, name: number) => {
    const record = list[key];
    if (record?.id) {
      deleteTemplateLevelList(record.id).then(() => {
        remove(name);
      });
    } else {
      remove(name);
    }
  };

  return (
    <>
      <div className="link-list">
        <Form.Item noStyle>
          <h4>
            {upperLevel?.levelName}与{lowerLevel?.levelName}匹配
          </h4>
        </Form.Item>
        <Form.List name={upperLevel.level}>
          {(fields, { add, remove }) => (
            <>
              {fields.map((field) => (
                <Space key={field.key} align="baseline">
                  <Form.Item
                    {...field}
                    key={`${field.key}-1`}
                    label={upperLevel?.levelName}
                    name={[field.name, 'upperFieldName']}
                  >
                    <Select style={{ width: 130 }}>
                      {(levelMetadata[upperLevel?.level] || []).map((item: any) => (
                        <Option key={item.key} value={item.fieldName}>
                          {item.title}
                        </Option>
                      ))}
                    </Select>
                  </Form.Item>
                  <SwapOutlined />
                  <Form.Item
                    {...field}
                    key={`${field.key}-2`}
                    label={lowerLevel?.levelName}
                    name={[field.name, 'lowerFieldName']}
                  >
                    <Select style={{ width: 130 }}>
                      {(levelMetadata[lowerLevel?.level] || []).map((item: any) => (
                        <Option key={item.key} value={item.fieldName}>
                          {item.title}
                        </Option>
                      ))}
                    </Select>
                  </Form.Item>
                  <MinusCircleOutlined onClick={() => deleteItem(remove, field.key, field.name)} />
                </Space>
              ))}
              <Form.Item>
                <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                  增加
                </Button>
              </Form.Item>
            </>
          )}
        </Form.List>
      </div>
    </>
  );
});

/**
 * @description: excel层级匹配关系
 * @param {any} props
 * @param {Ref} ref
 */
const ExcelLevel = (props: any, ref: Ref<unknown>) => {
  const { levelList, templateId, tplData, closeDialog } = props;
  const { activeBatch } = useBatchManageContext();
  const [form] = Form.useForm();

  // 高低层级列表
  const [infoList, setInfoList] = useState([]);
  // 层级关系列表
  const [levelRelationList, setLevelRelationList] = useState<any>({});
  // 不同层级的数据选项
  const [levelOptions, setLevelOptions] = useState<any>({});

  useImperativeHandle(ref, () => ({
    submit: () => {
      form.submit();
    }
  }));

  useEffect(() => {
    if (levelList && levelList.length > 0) {
      if (templateId) {
        // 获取层级关系列表
        fetchList();
      }

      // 整理不同层级数据
      setInfoList(
        levelList
          .map((level: ILevel, idx: number, arr: any[]) => {
            const next = arr[idx + 1];
            if (next) {
              return {
                key: level.level,
                upperLevel: level,
                lowerLevel: next
              };
            }
            return undefined;
          })
          .filter((item: any) => item)
      );
      initLevelOptions();
    }
  }, [levelList]);

  // 初始化选中的列作为层级数据选项
  const initLevelOptions = () => {
    // setLevelOptions();
    const _list = tplData?.levelList || [];
    _list.forEach((item: any) => {
      const { level } = item;
      !levelOptions[level] &&
        setLevelOptions((state: any) => ({
          ...state,
          [level]: _list
            .find((listItem: any) => listItem.level === level)
            .relationList.map((item: any) => ({
              ...item,
              key: level.column + level.title
            }))
        }));
    });
  };

  const formatItemData = (levelArr: any[]) => {
    const obj: any = {};
    levelArr.forEach((item: any) => {
      const linkObj = {
        id: item.id,
        upperFieldName: item.highLevelField.fieldName,
        lowerFieldName: item.lowLevelField.fieldName
      };
      if (obj[`${item.highLevelField.level}`]) {
        obj[`${item.highLevelField.level}`].push(linkObj);
      } else {
        obj[`${item.highLevelField.level}`] = [linkObj];
      }
    });
    setLevelRelationList(obj);
    return obj;
  };

  /**
   * @description: 获取层级对应列表
   */
  const fetchList = () => {
    fetchTemplateLevelList({ templateExcelId: templateId }).then((res) => {
      const levelArr = res.data?.levelFieldRelationList || [];
      form.setFieldsValue(formatItemData(levelArr));
    });
  };

  const onFinish = (values: any) => {
    const levelFieldRelationList = Object.entries(values)
      .map(([key, val]: any) => {
        const _info = infoList.find((item) => item.upperLevel.level === parseInt(key, 10));
        return _info
          ? val.map((item: any) => {
              return {
                id: item.id,
                highLevelField: {
                  fieldName: item.upperFieldName,
                  level: _info.upperLevel?.level
                },
                lowLevelField: {
                  fieldName: item.lowerFieldName,
                  level: _info.lowerLevel?.level
                }
              };
            })
          : [];
      })
      .flat();

    const params = {
      archiveTypeId: activeBatch.archiveTypeId,
      templateExcelId: templateId,
      levelFieldRelationList
    };

    saveTemplateLevelList(params).then((res) => {
      const levelArr = res.data?.levelFieldRelationList || [];
      form.setFieldsValue(formatItemData(levelArr));
      closeDialog();
    });
  };

  return (
    <div>
      <Form form={form} onFinish={onFinish} autoComplete="off">
        {infoList.map((item) => (
          <LevelLink
            levelMetadata={levelOptions}
            list={levelRelationList[item.upperLevel.level]}
            {...item}
          />
        ))}
      </Form>
    </div>
  );
};

export default forwardRef(ExcelLevel);
